<template>
	<view class="u-page">
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u--form labelPosition="left" :model="model1" ref="form1">
			<u-form-item label="头像" prop="userInfo.headImg" borderBottom ref="item1">
			<u-upload
				:fileList="fileList1"
				@afterRead="afterRead"
				@delete="deletePic"
				name="1"
				:multiple='false'
				
				:maxCount="1"
			></u-upload>
		
			</u-form-item>
			<u-form-item label="姓名" prop="userInfo.real_name" borderBottom ref="item1">
				<u--input v-model="model1.userInfo.real_name" border="none" placeholder="姓名,只能为中文"></u--input>
			</u-form-item>
			<u-form-item label="性别" prop="sex" borderBottom @click="showSex = true; hideKeyboard()"
				ref="item1">
				<u--input v-model="model1.sex" disabled disabledColor="#ffffff" placeholder="请选择性别"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item> 
			 
		  
			<u-form-item label="生日" prop="userInfo.birthday" borderBottom @click="showBirthday = true; hideKeyboard()"
				ref="item1">
				<u--input v-model="model1.userInfo.birthday" disabled disabledColor="#ffffff" placeholder="请选择生日"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>

		</u--form>
		<u-row>

			<u-col span="8" offset="2">
				<u-button type="primary" text="保存" customStyle="margin-top: 50px" @click="submit"></u-button>
			</u-col>
		</u-row>
		<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" 
			@close="showSex = false" @select="sexSelect">
		</u-action-sheet>

	 
		<u-datetime-picker :minDate="new Date(1970).getTime()" :maxDate='new Date().getTime()' :show="showBirthday" :value="birthday" mode="date" closeOnClickOverly
			@confirm="birthdayConfirm" @cancel="birthdayClose" @close="birthdayClose"></u-datetime-picker>

	</view>
</template>

<script>
var that
var UserInfo = require('../../../../service/UserInfo.js'),mUserInfo
var UpLoadFile = require( '../../../../tools/UploadTool.js'),mUpLoadFile ;
	export default {
		data() {
			return {
				
				fileList1:[],
				uploadUrl:'',
				disabled1: false,
				tips: '',
				value: '',
				showCalendar: false,
				showBirthday: false,
				model1: {
					sex:'',
					userInfo: {
						real_name: '楼兰',
						gender: 1,
						birthday: ''
					},
				},
				showSex: false,
				birthday: Number(new Date()),
				actions: [{
						name: '男',
						value:1
					},
					{
						name: '女',
						value:2
					}
				],
				rules: {
					'userInfo.real_name': [{
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					}, {
						// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
						validator: (rule, value, callback) => {
							// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
							return uni.$u.test.chinese(value);
						},
						message: "姓名必须为中文",
						// 触发器可以同时用blur和change，二者之间用英文逗号隔开
						trigger: ["change", "blur"],
					}],
				 
					'sex': {
						type: 'string',
						max: 1,
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
				 
			 
					'userInfo.birthday': {
						type: 'string',
						required: true,
						message: '请选择生日',
						trigger: ['change']
					},
				} 
			}
		},
		onLoad(){
			that = this
			mUserInfo = new UserInfo(that.mNetTool)
		},
		mounted() {
			let userInfo = uni.getStorageSync('userInfo')
			let isLogin = uni.getStorageSync('isLogin')
			console.log(userInfo)
			let a = {
				url:userInfo.avatar
			}
			this.fileList1= [{
					url: userInfo.avatar ,
				}]
			if(userInfo.gender == 1){
				this.model1.sex = '男'
			}else {
				this.model1.sex = '女'
			}
			if(isLogin){
				that.model1.userInfo = userInfo
			}else {
				uni.navigateTo({
					url:'../../login/login'
				})
			}
			mUpLoadFile = new UpLoadFile(that.mNetTool)
			that.uploadUrl = "https://test.iloomo.com/capi/tools/public/fileUpload?token=" + uni.getStorageSync('token') + "&fileName=" +'img'
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			that.$refs.form1.setRules(that.rules)
		},
		methods: {
						// 删除图片
						deletePic(event) {
							that[`fileList${event.name}`].splice(event.index, 1)
						},
						// 新增图片
						async afterRead(event) {
							// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
							let lists = [].concat(event.file)
							let fileListLen = that[`fileList${event.name}`].length
							lists.map((item) => {
								that[`fileList${event.name}`].push({
									...item,
									status: 'uploading',
									message: '上传中'
								})
							})
							for (let i = 0; i < lists.length; i++) {
								const result = await that.uploadFilePromise(lists[i].thumb)
								let item = that[`fileList${event.name}`][fileListLen]
								that[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
									status: 'success',
									message: '',
									url: result.fileUrl
								}))
								fileListLen++
							}
						},
						uploadFilePromise(url) {
							// let url = "https://test.iloomo.com/capi/tools/public/fileUpload?token=" + uni.getStorageSync('token') + "&fileName=" +'img'
							return new Promise((resolve, reject) => {
								// mUpLoadFile.uploadImg(url,res =>{
								// 	setTimeout(() =>{
								// 		// resolve(res.data.data)
								// 		console.log(res)
								// 	},1000)
								// })
								let a = uni.uploadFile({
									url: 'https://api.iloomo.com/capi/tools/public/fileUpload?token=08fee81482a84d388029f67ed57490cf', // 仅为示例，非真实的接口地址
									filePath: url,
									name: 'file',
									formData: {
										user: 'test'
									},
									success: (res) => {
										console.log(JSON.parse(res.data))
										setTimeout(() => {
											resolve(JSON.parse(res.data))
										}, 1000)
									}
								});
							})
						},

			groupChange(n) {
				// console.log('groupChange', n);
			},
			radioChange(n) {
				// console.log('radioChange', n);
			},
			navigateBack() {
				uni.navigateBack()
			},
			sexSelect(e) {
				that.model1.sex = e.name
				that.model1.userInfo.gender = e.value
				
				that.$refs.form1.validateField('userInfo.sex')
			},
			change(e) {
				// console.log(e);
			},
			formatter(day) {
				const d = new Date()
				let month = d.getMonth() + 1
				const date = d.getDate()
				if (day.month == month && day.day == date + 3) {
					day.bottomInfo = '有优惠'
					day.dot = true
				}
				return day
			},
			calendarConfirm(e) {
				that.showCalendar = false
				that.model1.hotel = `${e[0]} / ${e[e.length - 1]}`
				that.$refs.form1.validateField('hotel')
			},
			codeChange(text) {
				that.tips = text;
			},
	
			calendarClose() {
				that.showCalendar = false
				that.$refs.form1.validateField('hotel')
			},
			birthdayClose() {
				that.showBirthday = false
				that.$refs.form1.validateField('userInfo.birthday')
			},
			birthdayConfirm(e) {
				that.showBirthday = false
				that.model1.userInfo.birthday = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				that.$refs.form1.validateField('userInfo.birthday')
			},
			submit() {
				let userInfo = that.model1.userInfo
				userInfo.avatar = that.fileList1[0].url
				console.log(userInfo)
				uni.showToast({
					title:'请稍等',
					icon:'loading'
				})
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				that.$refs.form1.validate().then(res => {
					 mUserInfo.update(userInfo,res => {
						 console.log(res)
						 if(res){
							 uni.$u.toast('保存成功')
							 uni.setStorageSync('userInfo',res)
							 uni.navigateBack({
							 	
							 })
						 }else{
							 uni.$u.toast('保存失败')
						 }
					 })
					
				}).catch(errors => {
					uni.$u.toast('请检查信息')
				})
			},
			hideKeyboard() {
				uni.hideKeyboard()
			}
		},
	}
</script>

<style lang="scss">

</style>
